package com.sihan.swvp.common;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;

/**
 * 验证码生成类
 * 
 * @author xiaohu
 * 
 */
public class RandomImageGenerator {
	static Random random = new Random();

	/**
	 * 产生随机字体
	 * 
	 * @return
	 */
	static Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	/**
	 * 生成图片
	 * 
	 * @throws IOException
	 */
	public static String render(OutputStream out, int width, int height)
			throws IOException {
		BufferedImage buffImg = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g = buffImg.createGraphics();
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		Font font = new Font("Times New Roman", Font.HANGING_BASELINE, 28); // 设置字体。
		g.setFont(font);
		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}

		StringBuffer randomCode = new StringBuffer();

		int length = 4;
		String base = "0123456789";

		int size = base.length();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < length; i++) {
			int start = random.nextInt(size);
			String strRand = base.substring(start, start + 1);
			sb.append(strRand);
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));

			g.drawString(strRand, 15 * i + 6, 24);
			randomCode.append(strRand);
		}

		g.dispose();
		ImageIO.write(buffImg, "jpg", out);
		
		return sb.toString();
	}
}